package org.gy.T10.t2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DrawThread extends Thread{
    private Account acc;
    private double money;

    public DrawThread(Account acc, String name){
        super(name);
        this.acc = acc;
    }
    @Override
    public void run() {
// 取钱(⼩明，⼩红)
        acc.drawMoney(100000);
    }

    // ⼩明 ⼩红线程同时过来的
//    public void drawMoney(double money) {
//// 先搞清楚是谁来取钱？
//        String name = Thread.currentThread().getName();
//// 1、判断余额是否⾜够
//// this正好代表共享资源！
//        synchronized (this) {
//            if(this.money >= money){
//                System.out.println(name + "来取钱" + money + "成功！");
//                this.money -= money;
//                System.out.println(name + "来取钱后，余额剩余：" + this.money);
//            }else {
//                System.out.println(name + "来取钱：余额不⾜~");
//            }
//        }
//    }

    // 创建了⼀个锁对象
    private final Lock lk = new ReentrantLock();
    public void drawMoney(double money) {
// 先搞清楚是谁来取钱？
        String name = Thread.currentThread().getName();
        try {
            lk.lock(); // 加锁
// 1、判断余额是否⾜够
            if(this.money >= money){
                System.out.println(name + "来取钱" + money + "成功！");
                this.money -= money;
                System.out.println(name + "来取钱后，余额剩余：" + this.money);
            }else {
                System.out.println(name + "来取钱：余额不⾜~");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lk.unlock(); // 解锁
        }
    }
}
